<template>
  <a-form ref="formRef" style="padding-top: 20px" :model="formInfo" :rules="rules" v-if="type == 'add'">
    <a-row :gutter="24">
      <a-col :span="8">
        <a-form-item field="warehouseCode" label="目的仓库:" label-col-flex="100px">
          <a-select v-model="formInfo.warehouseCode" placeholder="请选择" value-key="id" allow-search @change="getInventoryData">
            <a-option v-for="(warehouse, i) in warehouseList" :key="i" :value="warehouse.warehouseCode" :label="warehouse.warehouseName" />
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="14">
        <a-form-item label="附件：" label-col-flex="100px">
          <div>
            <ul style="margin-right: 10px">
              <li v-for="(url, i) in formInfo.attachment" style="margin-bottom: 4px" :key="i">
                <a-tag color="arcoblue" closable>{{ url }}</a-tag>
              </li>
            </ul>
            <a-upload action="/" :custom-request="uplaodFile" :show-file-list="false">
              <template #upload-button>
                <a-button size="mini" type="outline">
                  <template #icon>
                    <icon-upload />
                  </template>
                  <template #default>上传附件</template>
                </a-button>
              </template>
            </a-upload>
          </div>
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="16">
        <a-form-item field="remark" label="备注：" label-col-flex="100px">
          <a-textarea v-model="formInfo.remark" placeholder=" " allow-clear />
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
  <a-form ref="formRef" :model="formInfo" v-else>
    <a-row :gutter="24">
      <a-col :span="12">
        <a-form-item label="目的仓库:" label-col-flex="100px">
          <p>{{ formInfo.warehouseName }}({{ formInfo.warehouseCode }})</p>
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="附件：" label-col-flex="100px">
          <div>
            <ul style="margin-right: 10px">
              <li v-for="(url, i) in formInfo.attachment" style="margin-bottom: 4px" :key="i">
                <a-tag color="arcoblue" closable @close="formInfo.attachment.splice(i, 1)">{{ url }}</a-tag>
              </li>
            </ul>
            <a-upload action="/" :custom-request="uplaodFile" :show-file-list="false">
              <template #upload-button>
                <a-button size="mini" type="outline">
                  <template #icon>
                    <icon-upload />
                  </template>
                  <template #default>上传附件</template>
                </a-button>
              </template>
            </a-upload>
          </div>
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="24">
        <a-form-item field="remark" label="备注：" label-col-flex="100px">
          <a-textarea v-model="formInfo.remark" placeholder=" " allow-clear />
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
  <div class="product-list-w">
    <div class="header flex-c">
      <p style="margin-right: 20px">已添加产品：{{ productList.length }}</p>
      <p>总数：{{ totalNum }}</p>
      <a-button v-if="addModel == 'purchasePlan'" style="margin-left: 20px" class="gray-outline" size="medium" @click="showChooseProductDialog = true">添加采购产品</a-button>
    </div>
    <div class="table-w" style="flex: 1">
      <a-table class="table-two-line" ref="tableRef" :bordered="false" :loading="tableLoading" :data="productList" :scroll="{ x: '100%', y: '100%' }" size="mini" :pagination="false">
        <template #columns>
          <a-table-column data-index="sort" title="序号" :width="45" fixed="left">
            <template #cell="{ rowIndex }">
              <p>{{ rowIndex + 1 }}</p>
            </template>
          </a-table-column>
          <a-table-column data-index="shop" title="站点/店铺" :width="120" fixed="left">
            <template #cell="{ record }">
              <p style="color: #ccc">{{ $extract(marketPlaceList[record.marketplaceId], 'name') }}</p>
              <TextLimit :rows="1" :val="record.shopName" />
            </template>
          </a-table-column>
          <a-table-column data-index="img" title="图片" :width="60" fixed="left">
            <template #cell="{ record }">
              <ImgPopover :src="record.productImg">
                <template #con>
                  <a-image width="40" height="40" fit="contain" :src="record.productImg" />
                </template>
              </ImgPopover>
            </template>
          </a-table-column>
          <a-table-column data-index="sku" title="SKU/类目" :width="130" fixed="left">
            <template #cell="{ record }">
              <ShowSpuDetailBySku :val="record.sku" :showLimit="true" :rows="1" />
              <p>{{ record.cateName || '--' }}</p>
            </template>
          </a-table-column>
          <a-table-column data-index="msku" title="MSKU/ASIN" :width="130" fixed="left">
            <template #cell="{ record }">
              <TextLimit :rows="1" :val="record.msku || '--'" />
              <TextLimit :rows="1" :val="record.asin || '--'" />
            </template>
          </a-table-column>
          <a-table-column data-index="productSpecs" title="SKU规格" :width="130">
            <template #cell="{ record }">
              <TextLimit :val="getProductSpecs(record)" />
            </template>
          </a-table-column>
          <a-table-column data-index="salesmanName" title="销售员" :width="140">
            <template #title>
              <p>
                <span class="warningColor">*</span>
                <span>销售员</span>
              </p>
            </template>
            <template #cell="{ record, rowIndex }">
              <a-space>
                <a-select v-model="record.salesman" placeholder="" value-key="id" style="width: 90px" allow-search>
                  <a-option v-for="(user, i) in userList" :key="i" :value="user" :label="user.userName" />
                </a-select>
                <a-button size="small" class="gray-outline" v-if="rowIndex === 0" @click="setGlobal(record, 'salesman')">
                  <template #icon>
                    <icon-double-down />
                  </template>
                </a-button>
              </a-space>
            </template>
          </a-table-column>
          <a-table-column data-index="purchaseDeptId" title="采购部门" :width="200">
            <template #title>
              <p>
                <span class="warningColor">*</span>
                <span>采购部门</span>
              </p>
            </template>
            <template #cell="{ record, rowIndex }">
              <a-space>
                <a-cascader style="width: 140px" :options="deptList" v-model="record.purchaseDeptId" placeholder="选择部门" :format-label="format" allow-search :field-names="{ value: 'id', label: 'deptName' }" check-strictly />
                <a-button size="small" class="gray-outline" v-if="rowIndex === 0" @click="setGlobal(record, 'purchaseDeptId')">
                  <template #icon>
                    <icon-double-down />
                  </template>
                </a-button>
              </a-space>
            </template>
          </a-table-column>
          <a-table-column data-index="amtPurchaseRecommend" title="推荐采购量" :width="80" />
          <a-table-column title="加急" :width="100">
            <template #cell="{ rowIndex, record }">
              <a-space>
                <a-switch v-model="record.urgent" checked-text="开" unchecked-text="关" />
                <a-button size="small" class="gray-outline" v-if="rowIndex === 0" @click="setGlobal(record, 'urgent')">
                  <template #icon>
                    <icon-double-down />
                  </template>
                </a-button>
              </a-space>
            </template>
          </a-table-column>
          <a-table-column :width="140">
            <template #title>
              <p>
                <span class="warningColor">*</span>
                <span>计划数量</span>
              </p>
            </template>
            <template #cell="{ record, rowIndex }">
              <a-space>
                <a-input-number v-model="record.planAmt" style="width: 90px" placeholder="" />
                <a-button size="small" class="gray-outline" v-if="rowIndex === 0" @click="setGlobal(record, 'planAmt')">
                  <template #icon>
                    <icon-double-down />
                  </template>
                </a-button>
              </a-space>
            </template>
          </a-table-column>
          <a-table-column :width="170">
            <template #title>
              <p>
                <span class="warningColor">*</span>
                <span>计划交期</span>
              </p>
            </template>
            <template #cell="{ record, rowIndex }">
              <a-space>
                <a-date-picker v-model="record.gmtPlanDelivery" style="width: 120px" :disabledDate="(current) => dayjs(current).isBefore(dayjs())" />
                <a-button size="small" class="gray-outline" v-if="rowIndex === 0" @click="setGlobal(record, 'gmtPlanDelivery')">
                  <template #icon>
                    <icon-double-down />
                  </template>
                </a-button>
              </a-space>
            </template>
          </a-table-column>
          <a-table-column title="产品备注" :width="80">
            <template #cell="{ record }">
              <div class="flex-c">
                <TextLimit :val="record.remark" :rows="1" />
                <div class="hover-edit">
                  <a-popconfirm @popup-visible-change="popupChange($event, record.remark)" @ok="updateSingle(record, 'remark')">
                    <template #content>
                      <p class="popconfirm-title">修改备注</p>
                      <a-textarea v-model="editVal" class="popconfirm-textarea" placeholder="修改备注，最多1000" allow-clear />
                    </template>
                    <icon-edit />
                  </a-popconfirm>
                </div>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="上期采购单价" :width="90">
            <template #cell="{ rowIndex }">
              <p>{{ getInventory(rowIndex, 'latestPurchaseUnitCosts') }}</p>
            </template>
          </a-table-column>
          <a-table-column title="可用库存" :width="80">
            <template #cell="{ rowIndex }">
              <p>{{ getInventory(rowIndex, 'amtInventory') }}</p>
            </template>
          </a-table-column>
          <a-table-column title="待入库存" :width="80">
            <template #cell="{ rowIndex }">
              <p>{{ getInventory(rowIndex, 'amtToBeIn') }}</p>
            </template>
          </a-table-column>
          <a-table-column title="计划采购量" :width="80">
            <template #cell="{ rowIndex }">
              <p>{{ getInventory(rowIndex, 'amtPlan') }}</p>
            </template>
          </a-table-column>
          <a-table-column title="采购中数量" :width="80">
            <template #cell="{ rowIndex }">
              <p>{{ getInventory(rowIndex, 'amtPurchase') }}</p>
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="60" fixed="right">
            <template #cell="{ rowIndex }">
              <a-button size="mini" type="text" v-if="productList.length > 1" @click="productList.splice(rowIndex, 1)">移除</a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </div>
  </div>
  <!-- 选择采购产品 -->
  <ChoosePurchaseProduct v-if="showChooseProductDialog" :isShow="showChooseProductDialog" @closed="showChooseProductDialog = false" @success="chooseProduct" />
</template>
<script lang="ts" setup>
  import { ref, onMounted, computed } from 'vue'
  import { findWarehouseListByParam } from '@/api/warehouse'
  import { marketPlaceList } from '@/utils/globalData'
  import { upload } from '@/api/base'
  import { Message } from '@arco-design/web-vue'
  import ChoosePurchaseProduct from './choosePurchseProduct.vue'
  import { findReplenishPage, findPurchaseAndInventoryData } from '@/api/purchase'
  import dayjs from 'dayjs'
  import { parseJson } from '@/utils'
  import useBaseDataStore from '@/store/modules/base-data'
  import { delateMenuChildren, treeFindPath } from '@/utils'

  const props = defineProps({
    addModel: {
      type: String,
      default: 'purchasePlan',
    },
    type: {
      type: String,
      default: 'add',
    },
    currentData: {
      type: Object,
      default: () => {},
    },
  })
  onMounted(() => {
    getUserList()
    getDeptList()
    console.log(props.currentData)
    if (props.type == 'add') {
      getWareHouseList()
    }
    // 智能补货获取选中的商品
    if (props.addModel == 'replenishment') {
      getProductList()
    } else if (props.type == 'edit') {
      getPurchaseDetail()
    }
  })
  // 合计计划数量
  const totalNum = computed(() => {
    return productList.value.reduce((acc, item: any) => {
      acc += Number(item.planAmt || 0)
      return acc
    }, 0)
  })
  const rules = ref({
    warehouseCode: [{ required: true, message: '请选择仓库' }],
  })
  const formRef = ref()
  const tableLoading = ref(false)
  const showChooseProductDialog = ref(false)
  const productList = ref<Array<any>>([])
  const warehouseList = ref<Array<any>>([])
  const editVal = ref<any>()
  const inventoryList = ref<Array<any>>([])
  const formInfo = ref<any>({
    attachment: [],
  })
  const useBaseData = useBaseDataStore()
  const userList = ref<Array<any>>([])
  const deptList = ref<Array<any>>([])

  // 获取所有用户列表
  async function getUserList() {
    await useBaseData.getUserList()
    userList.value = useBaseData.userList
  }
  // 获取所有用户列表
  async function getDeptList() {
    await useBaseData.getDeptList()
    deptList.value = delateMenuChildren(useBaseData.deptList || [])
  }
  function format(options: any) {
    const labels = options.map((option: any) => option.deptName)
    return labels?.[labels.length - 1]
  }
  // 获取库存信息
  async function getInventoryData() {
    inventoryList.value = []
    if (!formInfo.value.warehouseCode) return
    if (!productList.value.length) return
    let shopIds: Array<string> = []
    let skus: Array<string> = []
    productList.value.forEach((el: any) => {
      if (el.sku) skus.push(el.sku)
      if (el.shopId) shopIds.push(el.shopId)
    })
    let items = productList.value.map((el: any) => {
      return {
        warehouseCode: formInfo.value.warehouseCode,
        msku: el.msku,
        sellerId: el.sellerId,
        shopId: el.shopId,
        sku: el.sku,
      }
    })
    if (!skus.length) return
    const res: any = await findPurchaseAndInventoryData({ items })
    inventoryList.value = res?.data || []
  }
  // 显示明细库存
  function getInventory(i: any, key: string) {
    return inventoryList.value[i]?.[key]
  }
  // 获取仓库列表
  async function getWareHouseList() {
    const res = await findWarehouseListByParam()
    warehouseList.value = res.data || []
  }
  // 根据选中的id获取商品列表
  async function getProductList() {
    let idsStr = window.localStorage.getItem('addPurchasePalnIds')
    if (!idsStr) return
    tableLoading.value = true
    const res: any = await findReplenishPage({
      pageSize: 100,
      pageNum: 1,
      ids: idsStr,
    })
    tableLoading.value = false
    let list = res?.data?.records || []
    productList.value = list.map((el: any) => {
      return setItem(el)
    })
    getInventoryData()
  }
  // 初始化产品数据
  function setItem(item: any) {
    // 销售员
    if (item.salesmans?.[0]?.salesmanId) {
      item.salesman = {
        id: item.salesmans?.[0]?.salesmanId,
        userName: item.salesmans?.[0]?.salesmanName,
      }
    }
    item.planAmt = item.amtPurchaseRecommend
    item.productImg = item?.productImgs?.[0]
    item.remark = item?.productRemark
    item.urgent = false
    delete item.salesmans
    delete item.id
    delete item.productImgs
    return item
  }
  // 采购计划编辑
  function getPurchaseDetail() {
    formInfo.value = JSON.parse(JSON.stringify(props.currentData))
    formInfo.value.attachment = props.currentData.attachment ? props.currentData.attachment.split(',') : []
    let items = JSON.parse(JSON.stringify(props.currentData.billItems))
    productList.value = items.map((el: any) => {
      if (el.salesmanId) {
        el.salesman = {
          id: el.salesmanId,
          userName: el.salesmanName,
        }
      }
      return el
    })
    getInventoryData()
  }
  //设置全局
  async function setGlobal(item: any, key: string) {
    let val = item[key]
    productList.value.forEach((el) => {
      el[key] = val
    })
  }
  // 上传附件
  const uplaodFile: any = async (options: any) => {
    let { fileItem } = options
    let formData = new FormData()
    formData.append('file', fileItem.file)
    const res: any = await upload(formData)
    if (res?.data?.publicUrl) {
      formInfo.value.attachment.push(res.data.publicUrl)
    }
  }
  // 表格内容直接编辑
  function popupChange(state: boolean, val: any) {
    if (state) {
      editVal.value = val
    }
  }
  // 表格编辑备注
  async function updateSingle(item: any, editKey: string) {
    item[editKey] = editVal.value
  }
  // 校验信息
  async function validateData() {
    let valid = await formRef.value.validate((valid: any) => {
      return valid
    })
    if (valid) return false
    if (!productList.value.length) {
      Message.error('请最少选择一个产品')
      return false
    }
    for (let item of productList.value) {
      if (!item.planAmt || item.planAmt <= 0) {
        Message.error('计划采购数量必填并且必须大于0')
        return false
      }
      if (!item.salesman?.id) {
        Message.error('请选择销售员')
        return false
      }
      if (!item.purchaseDeptId) {
        Message.error('请选择采购部门')
        return false
      }
      if (!item.gmtPlanDelivery) {
        Message.error('计划交期必填')
        return false
      }
    }
    return true
  }
  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
  // 选中产品
  function chooseProduct(list: Array<any>) {
    list.forEach((el: any) => {
      let isHas = productList.value.find((item: any) => item.sku == el.sku && item.msku == el.msku && item.sellerId == el.sellerId && item.marketplaceId == el.marketplaceId)
      if (!isHas) {
        productList.value.push(setItem(el))
      }
    })
    getInventoryData()
  }
  // 获取保存数据
  function getSavaData() {
    let savaData = JSON.parse(JSON.stringify(formInfo.value))
    savaData.attachment = savaData.attachment?.join(',')
    savaData.purchaseItems = saveItemData()
    delete savaData.billItems
    return savaData
  }
  function saveItemData() {
    let list = JSON.parse(JSON.stringify(productList.value))
    list.forEach((el: any) => {
      el.salesmanId = el.salesman.id
      el.salesmanName = el.salesman.userName
      el.purchaseDeptId = el.purchaseDeptId
      let deptArr = treeFindPath(deptList.value, (data: any) => data.id == el.purchaseDeptId)
      el.purchaseDeptName = deptArr?.[deptArr.length - 1].deptName
      delete el.salesman
    })
    return list
  }

  defineExpose({ validateData, getSavaData })
</script>
<style lang="less" scoped>
  .arco-form {
    background-color: #fff;
    margin-bottom: 10px;
    padding-right: 20px;
  }
  .product-list-w {
    flex: 1;
    background-color: #fff;
    display: flex;
    padding: 0 20px;
    flex-direction: column;
  }
  .header {
    padding: 10px 0px;
    font-weight: bold;
  }
  .table-w {
    flex: 1;
    overflow: hidden;
  }
  .popconfirm-title {
    font-size: 14px;
    margin-bottom: 10px;
  }
  .popconfirm-textarea {
    width: 250px;
    height: 120px;
  }
</style>
